package com.cy.store.controller;

import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicateException;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("users")
public class UserController extends BaseControler{
    @Autowired
    private IUserService userService;

    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        /*http://localhost:8080/users/reg?username=controller&password=123456*/

            userService.reg(user);
            return new JsonResult<Void>(ok);
    }
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password , HttpSession session){
        User data = userService.login(username, password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        System.out.println("session中的Uid"+getUidFromSession(session));
        System.out.println("session中的name"+getUsernameFromSession(session));
        return  new JsonResult<User>(ok,data);
    }
    @RequestMapping("change_password")
    public  JsonResult<Void> changePassword(String oldPassword,
                                            String newPassword,
                                            HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changepassword(uid,username,oldPassword,newPassword);

        return new JsonResult<Void>(ok);
    }
}
